package com.cn.why.produce_pro.rabbit;

import com.cn.why.produce_pro.config.RabbitConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * 生产者
 */
@Component
public class ProducerMsg implements RabbitTemplate.ConfirmCallback {
    //日志
//    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入，为单例模式
    private RabbitTemplate rabbitTemplate;
    @Autowired
    public ProducerMsg(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }

    public void sendMsg(Map<String,Object> content, String exchange, String routingkey){
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());//消息唯一确定id
        //把消息放入ROUTINGKEY_A对应的队列当中去，对应的是队列A（先进入交换机再通过绑定的key值确定是否发送到对应的队列中）
        rabbitTemplate.convertAndSend(exchange, routingkey, content, correlationId);
    }

    /**
     * 回调
     * @param correlationData
     * @param b
     * @param s
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        System.out.println("回调id :"+correlationData);
        if(b){
            System.out.println("消息成功消费");
        }else {
            System.out.println("消息消费失败："+s);
        }
    }
}
